package com.jy.rhin.facade.listener;

import com.alibaba.fastjson.JSON;
import com.jy.rhin.application.basic.event.PublishMessageEvent;
import com.jy.rhin.sdk.dto.notification.NotificationMessageDto;
import com.jy.rhin.sdk.dto.notification.resp.PublishMessageDto;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author dhl
 * @date 2022/7/5
 * @Description
 */
@Component
@Slf4j
public class MessageMqListener {

    @Resource
    ApplicationEventPublisher eventPublisher;

    @RabbitListener(queues = "${rhin.amqp.listener.notificationQueue}")
    public void handleDelivery(Message message, Channel channel) {
        try {
            String body = new String(message.getBody());
            if (log.isDebugEnabled()) {
                log.debug("收到mq消息{}", body);
            }
            NotificationMessageDto content = NotificationMessageDto.from(body);
            List<PublishMessageDto> publishMessageList = JSON.parseArray(JSON.toJSONString(content.getData()), PublishMessageDto.class);
            eventPublisher.publishEvent(new PublishMessageEvent(publishMessageList));
        } catch (Exception e) {
            log.error("消息消费失败 ", e);
        } finally {
            try {
                //消息消费成功或者失败都ack确认，避免陷入死循环，失败时有补偿线程进行重试
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("确认消息失败 ", e);
            }
        }
    }
}
